package com.knowswift.issues.mqtt;


import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
@Slf4j
public class MqttService {


    private final MqttClient mqttClient;

    public MqttService(@Nullable MqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }

//    public boolean subscribe(String topic) {
//        try {
//            IMqttToken token = mqttClient.subscribeWithResponse(topic);
//            log.info("已订阅topic：{}", Arrays.toString(token.getTopics()));
//            return true;
//        } catch (MqttException e) {
//            log.error("订阅topic失败：" + topic, e);
//            return false;
//        }
//    }

    public boolean subscribe(String topic) {
        try {
            IMqttToken token = mqttClient.subscribeWithResponse(topic);
            log.info("已订阅topic：{}", Arrays.toString(token.getTopics()));
            return true;
        } catch (MqttException e) {
            log.error("订阅topic失败：" + topic, e);
            return false;
        }
    }


}
